import numpy as np
import threading
import tkinter as tk
import tracker
from detector import Detector
import copy
from PIL import Image, ImageTk
from A_star import main as a_star
from flask import Flask, render_template, request
import cv2
from datetime import timedelta
import os
import shutil
import subprocess
from utils.general import colorstr

app = Flask(__name__)
app.send_file_max_age_default = timedelta(seconds=1)

ALLOWED_EXTENSIONS = set(['FLV', 'AVI', 'MOV', 'MP4', 'WMV', 'flv', 'avi', 'mov', 'mp4'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


# def video_loop(output_image_frame):
#     current_image = Image.fromarray(output_image_frame)  # 将图像转换成Image对象
#     imgtk = ImageTk.PhotoImage(image=current_image)
#     panel.imgtk = imgtk
#     panel.config(image=imgtk)
n = 0
text = str(n)
i = 1
chi=0

@app.route('/', methods=['POST', 'GET'])
def index():
    def remove_file(folder_path):
        """
        递归清理文件夹
        """
        for item in os.listdir(folder_path):
            item_path = os.path.join(folder_path, item)
            if os.path.isdir(item_path):
                remove_file(item_path)
                os.rmdir(item_path)
                print(f'清理资源文件夹{item_path}')
            else:
                os.remove(item_path)

    def move_file(source_folder):
        """
        重命名生成文件
        """
        for filename in os.listdir(source_folder):
            source_file_path = os.path.join(source_folder, filename)
            if os.path.isfile(source_file_path):
                destination_file_path = os.path.join(source_folder, 'show.mp4')
                shutil.copy(source_file_path, destination_file_path)
                os.remove(source_file_path)
                print(f"检测文件存储路径为：{colorstr('bold', destination_file_path)}")

    def save_detect_source(input_file):
        """
        检测视频生成，文件名./runs/detect/exp/show.mp4
        """
        detected_path = './runs/detect'
        source_folder = './runs/detect/exp'
        remove_file(detected_path)
        subprocess.run(["python", "detect.py", "--source", input_file])
        move_file(source_folder)

    def showcapture(l, pth,chi):
        # save_detect_source(pth)
        detector = Detector()
        if chi==0:
            pth=0
        # 打开视频
        # pth=r"data\images\test1.mp4"
        capture = cv2.VideoCapture(pth)
        # capture = cv2.VideoCapture(0)
        # capture = cv2.VideoCapture('/mnt/datasets/datasets/towncentre/TownCentreXVID.avi')

        global n, i

        while i:
            # 读取每帧图片
            _, im = capture.read()
            if im is None:
                break

            # 缩小尺寸，1920x1080->960x540
            im = cv2.resize(im, (704, 416))

            list_bboxs = []
            bboxes = detector.detect(im)

            # 如果画面中 有bbox
            n = len(bboxes)
            if len(bboxes) > 0:
                list_bboxs = tracker.update(bboxes, im)

                # 画框
                # 撞线检测点，(x1，y1)，y方向偏移比例 0.0~1.0
                output_image_frame = tracker.draw_bboxes(im, list_bboxs, line_thickness=None)
                pass
            else:
                # 如果画面中 没有bbox
                output_image_frame = im
            pass
            # cv2.imshow('demo', output_image_frame)
            # l.pack_forget()
            l.place_forget()
            # l=tk.Label(window,text='人数'+str(n),bg='blue',font=('Arial',20))
            l.place(x=800, y=0)
            current_image = Image.fromarray(output_image_frame)  # 将图像转换成Image对象
            imgtk = ImageTk.PhotoImage(image=current_image)
            panel.imgtk = imgtk
            panel.config(image=imgtk)
            window.update()
            # window.after(1, video_loop(output_image_frame))
            key = cv2.waitKey(1)
            if key == 'q':
                capture.release()
                print('1')
                break
                cv2.destroyAllWindows()
            pass
        pass
        n = 0
        capture.release()
        i = 1
        current_image = Image.fromarray(black_img)  # 将图像转换成Image对象
        imgtk = ImageTk.PhotoImage(image=current_image)
        panel.imgtk = imgtk
        panel.config(image=imgtk)
        l.place_forget()
        # l=tk.Label(window,text='人数'+str(n),bg='blue',font=('Arial',20))
        # l.place(x=800,y=0)
        cv2.destroyAllWindows()

    def cancel():
        global i
        i = 0
    print(request.method)
    if request.method == 'POST':
        if request.form['submit'] == '摄像头检测':
            chi=0
            upload_path=0
            window = tk.Tk()
            window.title('火灾检测')
            window.geometry('1000x600')  # 这里的乘是小x
            # button_a = tk.Button(window, text='视频检测', font=('Arial', 12), width=10, height=2, command=showcapture)
            # button_a.place(x=800, y=120)
            panel = tk.Label(window, width=704, height=416)  # 摄像头模块大小
            black_img = np.zeros((416, 704)).astype(np.uint8)
            current_image = Image.fromarray(black_img)  # 将图像转换成Image对象
            imgtk = ImageTk.PhotoImage(image=current_image)
            panel.imgtk = imgtk
            panel.config(image=imgtk)
            panel.place(x=10, y=100)  # 摄像头模块的位置
            # window.config(cursor="arrow")
            button_a = tk.Button(window, text='视频检测', font=('Arial', 12), width=10, height=2,
                                 command=lambda: showcapture(l, upload_path, chi))
            button_a.place(x=800, y=150)
            # button_b = tk.Button(window, text='导航系统', font=('Arial', 12), width=10, height=2, command=a_star)
            # button_b.place(x=800, y=250)
            button_c = tk.Button(window, text='结束检测', font=('Arial', 12), width=10, height=2, command=cancel)
            button_c.place(x=800, y=350)
            # var = tk.StringVar()
            l = tk.Label(window, font=('Arial', 20))
            l.place(x=800, y=0)
            # var.set('人数'+str(n))
            window.mainloop()
            return render_template("app1.html")
        if request.form['submit'] == '上传视频':
            chi=1
            if len(request.files) == 0:
                return render_template('app1,html', message='请选择视频')
            else:
                f = request.files['picture']
                print(f)

                basepath = os.path.dirname(__file__)
                upload_path = os.path.join(basepath, 'static\images', f.filename)
                if not (f and allowed_file(f.filename)):

                    return render_template('app1.html', message='请选择视频文件，以FLV 、AVI、MOV、MP4、WMV为后缀.')
                else:
                    f.save(upload_path)
                    print(upload_path)
                    # save_detect_source(upload_path)
                    window = tk.Tk()
                    window.title('火灾检测')
                    window.geometry('1000x600')  # 这里的乘是小x
                    # button_a = tk.Button(window, text='视频检测', font=('Arial', 12), width=10, height=2, command=showcapture)
                    # button_a.place(x=800, y=120)
                    panel = tk.Label(window, width=704, height=416)  # 摄像头模块大小
                    black_img = np.zeros((416, 704)).astype(np.uint8)
                    current_image = Image.fromarray(black_img)  # 将图像转换成Image对象
                    imgtk = ImageTk.PhotoImage(image=current_image)
                    panel.imgtk = imgtk
                    panel.config(image=imgtk)
                    panel.place(x=10, y=100)  # 摄像头模块的位置
                    # window.config(cursor="arrow")
                    button_a = tk.Button(window, text='视频检测', font=('Arial', 12), width=10, height=2,
                                         command=lambda: showcapture(l,upload_path,chi))
                    button_a.place(x=800, y=150)
                    # button_b = tk.Button(window, text='导航系统', font=('Arial', 12), width=10, height=2, command=a_star)
                    # button_b.place(x=800, y=250)
                    button_c = tk.Button(window, text='结束检测', font=('Arial', 12), width=10, height=2, command=cancel)
                    button_c.place(x=800, y=350)
                    # var = tk.StringVar()
                    l = tk.Label(window, font=('Arial', 20))
                    l.place(x=800, y=0)
                    # var.set('人数'+str(n))
                    window.mainloop()
                    return render_template("app1.html")

    return render_template("app1.html")



if __name__ == '__main__':
    app.run()

